import QueryMaterial from '@/components/QueryMaterial';
import UserDefine from '@/components/UserDefine';
import {s_saveMaterialUserDefine, s_getMaterialCategoryTree, s_getMaterialDocument, s_getMaterialUserDefine, s_getOrgTargetKeysGlobal, s_getOrgTransferData, s_saveAllocateOrgGlobal, s_saveMaterialGroupInfo, s_saveUnitData, getCommTreeByXid, s_getTableInfo, s_getcommontableinfo, s_getmaterialgroup, s_operateInfo, s_queryBaseData } from '@/services/basis';
import { getSelection } from '@/services/selections';
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable } from '@ant-design/pro-components';
import { useModel, useRequest } from '@umijs/max';
import { Card, theme,Row,Col,Tree, Space, Button, Form, Input, Modal, Radio, Select, DatePicker, Drawer, Transfer, Divider, Checkbox, Tabs, TabsProps, message, Tag} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import moment from 'moment';
import React, { useRef, useState } from 'react';

//物料分类组件
 function CategoryTree(props:any){
   const [expandKeys,setExpandKeys]=useState<React.Key[]>([1]);
    //  setExpandKeys(props.expandKeys);
  return(
     
    <Tree 
         treeData={props.tdata}  
         blockNode={true}
         expandedKeys={expandKeys}  
         autoExpandParent={false}
         onExpand={(ekeys)=>{
            setExpandKeys(ekeys);
         }}
         onLoad={async ()=>alert(111)}
       onClick={(e,node)=>{props.getTreeInfo(node);}}/>
  );
}

 
//物料档案表组件-- 注意：table_ref用于外部控制表格还原
// function MaterialTable({tdata,setMaterialCode,table_ref}){
  function MaterialTable(props:any){
    return(
      <ProTable 
      dataSource={props.tdata} 
      columns={props.columns} 
      rowKey='id' 
      rowSelection={{
        type:'radio',
        onChange:(selectedKeys,selectedRows)=>{props.setMaterialCode(selectedRows)},
      }}
      scroll={{y:350,x:'150%'}}
      options={false}
      actionRef={props.table_ref}
      pagination={{
        size:'small',
        pageSize:9,
      }}
      />
     // onRow={(record)=>{return{onClick:()=>setMaterialCode(record.code)}}} />
   );

}

//物料自由项表，作为定义项--要调出所有自由项，并勾选
function MaterialUserDefine(props:any){

 //监控自定义值的变化.type代表更新的字段：1 item_id,2 ismust,3 status
 function update(e:any,id:number,type:number){
  const x=props.udata.map((item:any)=>{
      if(item.userdefine_id===id){
          if(type===1)
              return {...item,item_code:e.target.checked?1:0};
          else if(type===2)
              return {...item,ismust:e.target.value};
          else
              return {...item,status:e.target.value};
      }
     else
         return item;
  });

  //更新新值到staate, 同步渲染新表格--关键
  props.setUdata(x);
}

   interface DataType{
    apply_id:number,
    item_code:number,
    status:number,
    ismust:number,
    userdefine_id:number,
    code:string,
    name:string,
    //默认物料source_type=1
   } ;

   const columns:ProColumns<DataType>[]=[
    {
      dataIndex:'userdefine_id',
      title:'ID',
    },
    {
      dataIndex:'code',
      title:'自由项编码',
    },
    {
      dataIndex:'name',
      title:'自由项名称',
    },
    {
      dataIndex:'item_code',
      title:'选择',
      render:(text,record)=>
      <Checkbox checked={text===1?true:false} 
      // disabled={record.status===1?false:true}
          onChange={(e)=>update(e,record.userdefine_id,1)}>
      </Checkbox>
      
    },
    {
      dataIndex:'ismust',
      title:'取值类型',
      render:(text,record)=><Radio.Group value={text}  
      // disabled={record.status===1?false:true}
      onChange={(e)=>update(e,record.userdefine_id,2)}>
                        <Radio value={1}>必填</Radio>
                        <Radio value={0}>非必填</Radio>
                     </Radio.Group>
    },
    {
      dataIndex:'status',
      title:'状态',
      render:(text,record)=><Radio.Group value={text} 
      // disabled={text===1?false:true}
      onChange={(e)=>update(e,record.userdefine_id,3)}>
                        <Radio value={1}>启用</Radio>
                        <Radio value={2}>冻结</Radio>
                        <Radio value={3}>非选项</Radio>
                    </Radio.Group>
    },
   ];  

  // alert('这是控件内：'+JSON.stringify(udata));
   return(
    <ProTable 
    dataSource={props.udata} 
    columns={columns} 
    rowKey='id' 
   // rowSelection={{
    //  type:'radio',
    //  onChange:(selectedKeys,selectedRows)=>setUdata(selectedRows),    
   //  }}
    //onRow={(record)=>{return{onClick:()=>setUdata(record)}}}
    />
   );
}

interface DataType{
    id:number, 
    group_id:number,
    material_id:number, 
    quantity:number,
    material_status:number,
    materialgroup_status:number,
    operate_time:string,
    operater_code:string,
    group_name:string,
    materail_code:string,
    materail_name:string,
    invstd:string,
    invstd2:string,
    munit_name:string,
    userdefine_id:number,
    userdefine_doc_id:number,
    uvalue:string,
    uname:string,
    udocvalue:string,
}

const Welcome: React.FC = () => {
  //选中的物料分类码。因需用于新增表单中，故{}
  const [selectedCategory,setSelectedCategory]=useState(0);       //选择的分类ID
  const [selectedCateNode,setSelectedNode]=useState<{title:string}>();            //选择的树节点
  const [treeData,setTreeData]=useState();                        //分类树数据源
  const [tdata,setTdata]=useState();                               //档案表格数据源
  const [selectedRecords,setSelectedRecords]=useState<DataType[]>([]);           //选中的物料编码,
  const [columns,setColumns]=useState<any[]>([]);

  const [openInfo,setOpenInfo]=useState(false);//显示物料档案窗口
  const [openAllocate,setOpenAllocate]=useState(false);//显示物料分配窗口
  const [openDefine,setOpenDefine]=useState(false);//显示物料定义窗口
  const [etype,setEtype]=useState(0);   //1新增 0修改

  const [selectedKeys,setSelectedKeys]=useState<any[]>([]);//树选择的本级节点及下节点

  //const [orgtransfer,setOrgtransfer]=useState();//穿梭框数据源
  const [orgtargetkeys,setOrgtargetkeys]=useState([]);//穿梭框的已选中值
  const [userDefine,setUserDefine]=useState({});
  const [data,setData]=useState<{material:any,userdefine:any}>({material:null,userdefine:null});

   //定义物料自由项
   const [udata,setUdata]=useState([]);//在表格中更新选择状态
   //定义计量单位 组件数据源
   const [uintSelection,setUintSelection]=useState([]);

   const eform_ref=useRef<ProFormInstance>();//物料编辑表单
   const table_ref=useRef<ActionType>();//用于向物料档案组件表传递引用
   const [expandKeys,setExpandKeys]=useState([]);
   
    //在MODEL中,定义FORM供调用
  // const orgtransfer=useModel('getOrgTransfer');//角色分配的组织穿梭框数据源--直 接使用
 
 //此处创建一个生成树的通用方法，通过传入表名和X_ID值
 useRequest(()=>getCommTreeByXid({x_id:1,source_table:'materialgroup_category'}),{  
  onSuccess:(data)=>{
    setTreeData(data.ctree);
    setExpandKeys(data.keys);
  },
});

  //获取物料组明细表
 useRequest(()=>s_getmaterialgroup({x_id:1,tdata:[]}),{
         onSuccess:(data:any)=>{
          //  alert(JSON.stringify(data));
            setTdata(data[0]);
            generalCol(data);
         },
     }
  );
 
  function generalColLabel(c:string){
        var lab='';
        switch(c){
          case 'quantity': lab='数量';break;
          case 'material_status': lab='物料状态';break;
          case 'materialgroup_status': lab='组状态';break;
          case 'group_name': lab='组名称';break;
          case 'material_code': lab='物料编码';break;
          case 'material_name': lab='物料名称';break;
          case 'invstd': lab='规格';break;
          case 'invstd2': lab='型号';break;
          case 'munit_name': lab='计量单位';break;
          case 'status': lab='状态';break;
          case 'operater_name': lab='操作人';break;
          case 'operate_time': lab='操作时间';break;
          default : lab=c;     
        }
        return lab;
  }
   
  function generalColHidden(c:string){
    return ['id','x_id','group_id','material_id','mid','operater_id'].includes(c)?true:false;
  }

  function generalCol(tdata:any[]){
     if(tdata[0].length>0){
         var col=Object.keys(tdata[0][0]);
         var col2:any[]=[];
         col.map((item)=>{
           col2.push({
                       dataIndex:item,
                       title:generalColLabel(item),
                       hidden:generalColHidden(item),
                       render:(text:any)=>{
                         switch(item){
                          case 'status' : return text=='1'?<Tag>正常</Tag>:text==2?<Tag color='blue'>冻结</Tag>:<Tag color='red'>删除</Tag>;break;
                          case 'operate_time' : return moment(moment(text).toDate()).format('YYYY-MM-DD');break;
                          default :return text;
                         }
                       },
                       fixed:item=='status'?'right':false,
                       width:item=='status'?80:null,
                  });
          }); 
          // alert(JSON.stringify(col2));
          setColumns(col2);
     }
  }
//获取计量单位表
useRequest(()=>getSelection({source:'base_unit',code:'999'}),{
    onSuccess:(data:any)=>{
      const x=data.map((item:any)=>({value:item.code,label:item.name}));
      setUintSelection(x);
    }
});
 
  //根据左侧选择的类别，右侧表格显示明细--注意：此处传入的是树节点node(key,title) 
  //---先取本节点及下级节点值，再共同选---------------------------------------------开始-----------------
  var arr:any[]=[];
   //定义一个递归函数，获取选中节点下的所有key
   function getNodeKeys(node:{key:any,title:any,children:any[]}){
        if(node.children.length>0)
              node.children.map((item:any)=>{
                 arr.push(item.key);
                 if(item.children.length>0){
                      arr.push(getNodeKeys(item));
                 }
             });
      }

  async function getMaterial(node:any){
     // alert( (curCategory));
      setSelectedRecords([]);
      setSelectedCategory(node.key);
      setSelectedNode(node);
     
     arr=[];//先置为空，再取数据
     arr.push(node.key);
     getNodeKeys(node);
     setSelectedKeys(arr.filter((item)=>item!=null));//当前选中的组织的所有下级ID

     const x=await s_getmaterialgroup({x_id:1,tdata:arr});
     //alert(JSON.stringify(x.data[0]));
     setTdata(x.data[0]);
     table_ref.current?.reset?.();
  }
 //---先取本节点及下级节点值，再共同选---------------------------------------------结束-----------------

  //新增物料信息
  async function addMaterialInfo(){
       if(selectedCategory===0)
          message.warning('请先选择物料组分类。');
       else{
          setEtype(1);
          // alert(JSON.stringify(selectedCategory));
          //根据选
           //参数source_type:1为物料，2为客商（暂未使用）
          const x=await s_getMaterialUserDefine({x_id:1,source_type:1,item_id:0});  
          setData({material:null,userdefine:null}); 

         //物料自由项
          setUdata(x.data[0]);
          setOpenInfo(true);
       }
  }

  //编辑物料信息
  async function editMaterialInfo(){
     if(selectedRecords.length===0)
         message.warning('请先选择要修改的物料。');
      else{
        setEtype(0);
        setData({material:null,userdefine:null});  
      //获取物料对应的自定义项
      // const x=await s_getTableInfo({x_id:1,source:'v_userdefineapply',id:selectedRecords[0].material_id});
      // alert(JSON.stringify(x.data));
      //  setUserDefine(x.data);
       setOpenInfo(true);
       setUserDefine({});
       
       //获取自由项
       const y=await s_queryBaseData({x_id:1,source:'v_material',
                                    tdata:{id:selectedRecords[0].material_id,gid:selectedRecords[0].id}});
      //  alert(JSON.stringify(y.data[1]));
       setData({material:null,userdefine:y.data[1]});
       var u={};
      //  alert(JSON.stringify(y.data[2]));
        y.data[2].map((item:{userdefine_id:any,value:any})=>{
           var a='uitem'+item.userdefine_id;
           u[a]=item.value;
       });
      //  alert(JSON.stringify(u));
       setUserDefine(u);
       eform_ref.current?.setFieldsValue({...u});
       //
      };
  }

  //保存物料编辑信息
  async function saveMaterialInfo(){
     //先取表单的数据，再保存。
     const fdata0=eform_ref.current?.getFieldsValue();
     var fdata={...fdata0,
                // ...userDefine,
                   id:selectedRecords[0]?.id, 
                   operate_time:moment(moment(fdata0.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss')};
     const keys=Object.keys(fdata);  
     var uitem:any[]=[];
    //  alert('uitem1'.indexOf('uitem'));
     keys.map((item:any)=>{
        if(item.indexOf('uitem')==0){
            uitem.push({userdefine_id:item.substring(5),value:fdata[item]});
            // alert(JSON.stringify(uitem));
        }
     });   
     fdata={...fdata,userdefine:uitem} ;        
      // alert('待保存数据：'+JSON.stringify(fdata));
      // alert(JSON.stringify(uitem));
     //调用远程服务保存 
     const x=await s_saveMaterialGroupInfo({x_id:1,operater_id:1,etype,fdata});
     //保存自定义信息
     // alert(JSON.stringify(selectedRecords[0]));
    //  const y=await s_saveMaterialUserDefine({x_id:1,operater_id:1,item_id:selectedRecords[0]?.id,fdata:udata}); 
                
     if(x.success){
        message.success('数据保存成功。');
        setOpenInfo(false);
        setTdata(x.data);
     
        //更新物料档案表
        table_ref.current?.reloadAndRest?.();
      }
      else
        message.error('数据保存失败，请检查。');
  }

  async function  operateInfo(type:number){
    // source,x_id,operater_id,otype,id
    const x=await s_operateInfo({source:'materialgroup',id:selectedRecords[0].id,otype:type,x_id:1,operater_id:1});
    if(x.success){
      message.success('操作成功！');
      const x=await s_getmaterialgroup({x_id:1,tdata:arr});
     //alert(JSON.stringify(x.data[0]));
      setTdata(x.data[0]);
      table_ref.current?.reloadAndRest?.();
    }else
      message.error('操作失败，请检查。');
       
  }
 
  //定义窗体引用
  const [formInfo]=Form.useForm();      //物料信息
  const [formAllocate]=Form.useForm();  //物料分配
  const [formDefine]=Form.useForm();    //物料定义
   
  //调用组织分配的界面
  async function allocateOrg(){
    if(selectedRecords.length===0)
        message.warning('请先选择要分配的物料。');
    else{
   //定义组织分配的数据源 s_getOrgTargetKeysGlobal({item_type,item_code})获取已分配的组织CODE
  // s_getOrgTransfetData（）获取组织列表，返回[{code,name}],需进一步组装为[{key,title}]
   //const x=await s_getOrgTransferData({});   
   //alert(JSON.stringify(orgtransfer2));                                     //--通用--
   //setOrgtransfer(orgtransfer2?.map((item:any)=>{return {key:item.code,title:item.name}}));
   //注意：要先获取item_code对应具体的物料编码---selectedCode
   
   const y=await s_getOrgTargetKeysGlobal({x_id:1,item_type:6,item_id:selectedRecords[0]?.id}); //---通用---
   const y0=y.data.map((item:any)=>item.id);
   //设置state
   //alert(JSON.stringify(x0));
  // alert(JSON.stringify(y));
   //setOrgtransfer(x0);
   setOrgtargetkeys(y0);
    setOpenAllocate(true)
     }
  }

  //保存分配组织
  async function saveAllocateOrgRole(){
    const x=await s_saveAllocateOrgGlobal(
         {x_id:1,operater_id:1,item_type:6,item_id:selectedRecords[0]?.id,fdata:orgtargetkeys});
    if(x.success){
      message.success('数据保存成功。');
      setOpenAllocate(false);
      
    }
    else
      message.error('数据保存失败，请检查');
  }
  
  
  //定义物料详细信息标签，以Tabs显示
  const items:TabsProps['items']=[
    {
      key:'1',
      label:'基本信息',
      children:<>
       <ProForm formRef={eform_ref} name='eform'
        submitter={false} layout='horizontal' labelAlign='left'
        onFinish={()=>saveMaterialInfo()}
        initialValues={etype===1?{status:1,operate_time:moment().format('YYYY-MM-DD'),
                           group_id:selectedCategory,
                       }
                       :{...selectedRecords[0],
                        //  ...userDefine,
                         operate_time:moment(moment(selectedRecords[0]?.operate_time)).format('YYYY-MM-DD'),
                       }}
        
        >
           <Row gutter={8}>
            <Col span={10}>
            <QueryMaterial  setData={setData} componentRef={eform_ref}  />
            {/* {"这是组件返回的数据："+JSON.stringify(data.userdefine)} */}
            
            {/* <UserDefine udata={[{userdefine_id:1,userdefine_name:'XXXX'}]}/> */}
             <ProFormText name='id' label='组-行数据ID'  hidden/>
             <ProFormText name='group_id' label='组ID'  hidden/>
             <ProFormText name='material_id' label='物料ID'  hidden/>
             <ProFormText name='material_code' label='物料编码'  width={300} disabled
                rules={[{required:true,message:'必须选择物料。'
                }]}
                />
            <ProFormText name='material_name' label='物料名称' disabled width={300} />
            <ProFormText name='invstd' label='规格' disabled width={300} />
           <ProFormText name='invstd2' label='型号' disabled width={300} />
           <ProFormText name='munit_name' label='单位' disabled width={300} />
           </Col>
            <Col span={2}></Col>
            <Col span={10}>
            {/* 自由项列表 */}
            {/* {JSON.stringify(userDefine)} */}
            {/* <UserDefine udata={data.userdefine}/> */}
            {/* {  toUserDefine(data.userdefine) } */}
           {
         data.userdefine!=null&&data.userdefine.length>0?(
             data.userdefine.map((item:any)=>{
                 if(item.input_style==1)
                       return   <ProFormText name={'uitem'+item.userdefine_id} label={item.userdefine_name} /> 
                 else if(item.input_style==2){
                     //  alert(JSON.stringify(item.value));
                      const opt=JSON.parse(item.value).map((item2:any)=>
                                ({value:item2.substring(0,item2.indexOf('-')),
                                 label:item2.substring(item2.indexOf('-')+1)}));
                        return   <ProFormSelect  name={'uitem'+item.userdefine_id} label={item.userdefine_name}  
                                   options={opt}
                                   /> 
                 }
                })

            ):<></>
          }
            {/* {true?<><ProFormText name='TEST' label='TEST'/><ProFormText name='test2' label='test2'/></>:<Button>yyyyy</Button>} */}
            <ProFormText name='quantity' label='数量'
               rules={[{required:true,message:'必须输入数量'}]} />
            <ProFormRadio.Group name='status' label='状态'  width={300} 
              options={[{value:1,label:'启用'},{value:2,label:'停用'},{value:3,label:'删除'}]}
              />
          <ProFormDatePicker name='operate_time' label='操作时间' width={300} />
          <ProFormText name='operater_code' label='操作人' width={300} />
            </Col>
            
               </Row>
        </ProForm>
      </>
    },
    // {
    //   key:'2',
    //   label:'自由项',
    //   children:<>
    //       <MaterialUserDefine udata={udata} setUdata={setUdata}/>
    //   </>
    // }
  ];

  function onClose(){
    setOpenInfo(false);
  }
  
  function getTreeNodeInfo(arg0: { key: React.Key; title: string | undefined; }): void {
    throw new Error('Function not implemented.');
  }

  return<>
     <Row gutter={10}>
     <Col  span={6}>
     <Card title='物料组分类' style={{height:'75vh'}}>
         {/* <CategoryTree tdata={treeData} getTreeInfo={getMaterial}  expandKeys={expandKeys}/> */}
         <Tree treeData={treeData} expandedKeys={expandKeys} 
            onExpand={(ekeys:any)=>setExpandKeys(ekeys)}
            //  onClick={(e,node)=>getTreeNodeInfo({key:node.key,title:node.title?.toString()})}
              onClick={(e,node)=>{getMaterial(node);}}
         />
     </Card>
     </Col>
     <Col  span={18}>
      <Card title='物料组明细'  style={{height:'75vh'}} id='drawer_id'
      extra={<Space size='large'>
      <Button  onClick={()=>addMaterialInfo()}>新增物料组明细</Button>
      <Button  onClick={()=>editMaterialInfo()}>修改物料组明细</Button>
      <Button onClick={()=>operateInfo(1)}>启用</Button>
      <Button onClick={()=>operateInfo(2)}>冻结</Button>
      <Button onClick={()=>operateInfo(3)}>删除</Button>
      {/* <Button  onClick={()=>allocateOrg()}>分配组织</Button> */}
      
      </Space>}
      >
       {/* {JSON.stringify(selectedRecords)} */}
       {/* {userDefine} */}
       <MaterialTable tdata={tdata} 
          setMaterialCode={setSelectedRecords} 
          table_ref={table_ref} columns={columns} />

       {/* <Drawer title='分配组织' placement='bottom' open={openAllocate} 
        onClose={()=>setOpenAllocate(false)}   getContainer={false}
        extra={<Button onClick={()=>saveAllocateOrgRole()}>保存</Button>}>  
            <Transfer  style={{marginLeft:90}}
            titles={['未分配组织','已分配组织']}
            dataSource={orgtransfer} //在原基础上组装为格式
            targetKeys={orgtargetkeys}
            render={(item:any)=>item.title}
            onChange={(tkeys:any,direction,mkeys)=>setOrgtargetkeys(tkeys)}            
            />
      </Drawer> */}

      {/* <Drawer title='物料管理' placement='bottom' open={openDefine} 
        onClose={()=>setOpenDefine(false)}   getContainer={false}
        extra={ <Button>保存</Button>}>  
             用于各组织，管理各自物料：在保持物料原有信息基础上，再定义附加的信息等。
      </Drawer> */}

      </Card>
      </Col>
     </Row>

    
     <Modal title='物料组维护' open={openInfo}  width='80%'   maskClosable={false}  okButtonProps={{hidden:true}}
         destroyOnClose={true} closable={true} onCancel={()=>onClose()} cancelButtonProps={{hidden:true}}
         onClose={()=>onClose()}  
     
     >  
       <ProCard 
          extra={<Space size='large'>
            <Button onClick={()=>eform_ref.current?.submit()} >保存</Button>
            <Button onClick={()=>setOpenInfo(false)} >取消</Button>
          </Space>}  >
          {/* <QueryMaterial  setData={setData} /> */}
          {/* {JSON.stringify(data)} */}
           <Tabs items={items} type='card' />
       </ProCard>  
     </Modal>

     
  </>
};

export default Welcome;


